package com.wj.core.common.util;

import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author: wangjun
 * @create: 2018-06-04 
 **/
public class PropertiesUtil {

  public static String resourcePath = null;

  static {
    resourcePath = PropertiesUtil.class.getClassLoader().getResource("").getPath();
  }

  public static void getProperties(String filePath) {
    Properties prop = null;
    try {
      // 通过Spring中的PropertiesLoaderUtils工具类进行获取
      prop = PropertiesLoaderUtils.loadAllProperties(filePath);
      printAllProperty(prop);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 根据key读取value
   *
   * @param filePath
   * @param keyWord
   * @return String
   * @throws
   */
  public static String getPropertiesByKey(String filePath, String keyWord) {
    Properties prop = new Properties();
    String value = null;
    try {
      // 通过输入缓冲流进行读取配置文件
      InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
      // 加载输入流
      prop.load(InputStream);
      // 根据关键字获取value值
      value = prop.getProperty(keyWord);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return value;
  }

  /**
   * @param props
   * @return void
   * @throws
   */
  private static void printAllProperty(Properties props) {
    @SuppressWarnings("rawtypes")
    Enumeration en = props.propertyNames();
    while (en.hasMoreElements()) {
      String key = (String) en.nextElement();
      String value = props.getProperty(key);
      System.out.println(key + " : " + value);
    }
  }

  public static void main(String[] args) {
    String path = "config/wj-config.properties";
    String key = "ZkService.address";
    System.out.println("resource path :" + resourcePath);
    String propertiesByKey = getPropertiesByKey(resourcePath + path, key);
    System.out.println("result ====>" + propertiesByKey);
  }
}
